package club.tclyq.good_time.photowall.show.service;

import club.tclyq.good_time.common.config.bean.ViewConfigBean;
import club.tclyq.good_time.common.utils.JsonUtils.JsonUtils;
import club.tclyq.good_time.upload.bean.Photo;
import club.tclyq.good_time.upload.repository.PhotoRepository;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.groupingBy;

/**
 * @author tanchong
 * Create Date: 2019/2/24
 */
@Service
public class ShowPhotoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ShowPhotoService.class);
    private PhotoRepository photoRepository;
    private MongoTemplate mongoTemplate;
    private int singlePageCount;

    @Autowired
    public ShowPhotoService(PhotoRepository photoRepository,
                            ViewConfigBean viewConfigBean,
                            MongoTemplate mongoTemplate) {
        this.photoRepository = photoRepository;
        this.mongoTemplate = mongoTemplate;
        singlePageCount = viewConfigBean.getSinglePageCount();
    }

    public Map<String, List<Photo>> getPhotoToPage(HttpServletRequest request){

        // 照片ID参数是否存在，如果存在则转换成ObjectID。
        ObjectId lastPhotoObjId = null;
        if (!request.getParameter("lastPhotoId").equals("")) {
            try {
                var lastPhotoId = request.getParameter("lastPhotoId");
                String s = String.valueOf(lastPhotoId);
                lastPhotoObjId = new ObjectId(s);
            } catch (IllegalArgumentException e) {
                // 不用做任何事，下面会对lastLogId进行空值判断。
                LOGGER.info("error：： {}",e);
            }
        }
        if(lastPhotoObjId == null){
            LOGGER.info("lastPhotoObjId is null : {}",lastPhotoObjId);
            return getPhotoFirstPage();
        }else {
            LOGGER.info("lastPhotoObjId not null : {}",lastPhotoObjId);
            return getPhotoNextPage(lastPhotoObjId);
        }
    }

    /**
     * 获取第一版照片
     */
    private  Map<String, List<Photo>> getPhotoFirstPage(){

        return photoRepository.findTop10ByOrderByIdDesc()
                .stream()
                .collect(groupingBy(Photo::getType));
    }

    private Map<String ,List <Photo>> getPhotoNextPage(ObjectId lastPhotoId){
        var query = new Query();
        var sort = Sort.by(Sort.Direction.DESC,"_id");
        query.addCriteria(new Criteria("_id").lt(lastPhotoId));
        query.limit(singlePageCount);
        return mongoTemplate.find(query.with(sort), Photo.class).stream().collect(groupingBy(Photo::getType));
    }

}
